package com.summer.NIO;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.Pipe;
import java.nio.channels.Pipe.SinkChannel;
import java.nio.channels.Pipe.SourceChannel;

public class PipeCase1 {
	public static void main(String[] args) throws IOException {
		Pipe pipe = Pipe.open();

		ReadTask readTask = new ReadTask(pipe);
		WriteTask writeTask = new WriteTask(pipe);
		
		readTask.start();
		writeTask.start();
	}
	
	public static class WriteTask extends Thread{
		
		private SinkChannel sinkChannel;
		
		public WriteTask(Pipe pipe){
			sinkChannel = pipe.sink();
		}
		
		@Override
		public void run() {
			String newData = "New String to write to file..." + System.currentTimeMillis();
			ByteBuffer buf = ByteBuffer.allocate(48);
			buf.clear();
			buf.put(newData.getBytes());

			buf.flip();

			while(buf.hasRemaining()) {
			    try {
					System.out.println("准备写~~~~");
					sleep(5000);
					sinkChannel.write(buf);
					System.out.println("写完了~~~~");
				} catch (IOException | InterruptedException e) {
					e.printStackTrace();
				}
			}

		}
	}
	
	public static class ReadTask extends Thread{

		private SourceChannel sourceChannel;

		
		public ReadTask(Pipe pipe){
			sourceChannel = pipe.source();
		}
		
		@Override
		public void run() {
			
			ByteBuffer buf = ByteBuffer.allocate(48);
			try {
				System.out.println("准备读~~~~");
				int bytesRead = sourceChannel.read(buf);
				
				buf.flip();
				byte[] readBytes = new byte[buf.limit()];
				buf.get(readBytes,0,readBytes.length);
				
				System.out.println("读完了："+new String(readBytes));
				
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	
}
